﻿var allServices = [];
var bouquetSelected;
var bouquet;
var currChannel;
var servicesLoaded = false;
var connected;

$(function () {
    $.ajaxSetup({
        // Disable caching of AJAX responses
        cache: false
    });
    $(document).bind('pageinit', function (event, data) {
        
        window.console = {
            log: function (str) { window.external.Notify(str); }
        };

        // output errors to console log
        window.onerror = function (e) {
            console.log("window.onerror ::" + JSON.stringify(e));
        };
        
        $.get(getPath(uri.currService, ''), function (current) {
            currChannel = current;
            //$.get(uri.receiver + "/cgi-bin/getServices?ref=1:15:fffffffe:12:ffffffff:0:0:0:0:0:", function (data) {
            //    getAllServices(current, data);
            //    servicesLoaded = true;
            //});
        });
    });

    $('#bouquets').bind('pagebeforeshow', function (event, data) {
        try {
           // window['localStorage'] !== null;

            var r = localStorage.setItem('a', 'b');
            var a = localStorage.getItem('a');
            //var t = typeof (localStorage) == 'undefined';
            alert(a);

            $.get(uri.receiver + uri.getServices + "4097:7:0:6:0:0:0:0:0:0:", function (data) {
                DisplayBouquets(data);
            });
        }
        catch (err) { alert(JSON.stringify(err)); }
    });

    $('#channels').bind('pagebeforeshow', function (e, data) {
        try {
            if (bouquet) {
                $.get(uri.receiver + bouquet.uri, function (data) {
                    DisplayChannels(bouquet.name, data);
                });
            }
            else {
                $.get(uri.receiver + uri.getServices + "4097:7:0:6:0:0:0:0:0:0:", function (data) {
                    var bouquets = getBouquets(data);
                    var bouquet = getSelectedBouquet(bouquets);
                    $.get(uri.receiver + uri.getServices + bouquet.command, function (data) {
                        DisplayChannels(bouquet.name, data);
                    });
                });
            }
        }
        catch (err) { alert(err.message); }
    });

    $('#epg').bind('pagebeforeshow', function (event, data) {
        try {
            //localStorage.setItem("username", "John");
            //var test = '<!DOCTYPE html><body><table><tr><td></td><tr></table></body></html>'
            //alert($('body', test).html());
                //window.localStorage.setItem("item_key", "value I am storing");
                //var data = localStorage.getItem("item_key");
                //alert(data);

            $.get(getPath(uri.currEPG, ''), function (data) {
                try {
                    $(data).find('tbody tr td:nth-child(2)').each(function () {
                        data = data.replace($(this).html(), '');
                    });
                    var content = data.split('<body>')[1].split('</body>')[0];
                    $('#epgContent').html(content);
                }
                catch (err) { alert(err.message)}
            });
        }
        catch (err) { alert(err.message); }
    });

    $('#viewEPG').click(function (event) { $.mobile.changePage('index.html#epg'); });

    $('#rcPower').click(function (event) { $.get(getPathRC(RemoteControl.power)); });
    $('#rcOK').click(function (event) { $.get(getPathRC(RemoteControl.ok)); });
    $('#rcCancel').click(function (event) { $.get(getPathRC(RemoteControl.cancel)); });
    $('#rcInfo').click(function (event) { $.get(getPathRC(RemoteControl.info)); });
    $('#rcOKcnl').click(function (event) {
        var channel = $('#number-1').val();
        for (var i = 0; i < channel.length; i++) {
            $.get(getPathRC(RemoteControl[channel[i]]));
        }
        $.get(getPathRC(RemoteControl.ok));
        $('#number-1').val('')
    });
    $('#rcVolumeUp').click(function (event) { $.get(getPathRC(RemoteControl.volumeUp)); });
    $('#rcVolumeDown').click(function (event) { $.get(getPathRC(RemoteControl.volumeDown)); });
    $('#rcMute').click(function (event) { $.get(getPathRC(RemoteControl.mute)); });
    $('#rcDream').click(function (event) {$.get(getPathRC(RemoteControl.dream));});
    $('#rcAudio').click(function (event) {$.get(getPathRC(RemoteControl.audio));});
    $('#rcVideo').click(function (event) {$.get(getPathRC(RemoteControl.video));});
    $('#rcNavUp').click(function (event) {$.get(getPathRC(RemoteControl.up));});
    $('#rcNavDown').click(function (event) {$.get(getPathRC(RemoteControl.down));});
    $('#rcNavLeft').click(function (event) {$.get(getPathRC(RemoteControl.left));});
    $('#rcNavRight').click(function (event) {$.get(getPathRC(RemoteControl.right));});
    $('#rcRed').click(function (event) {$.get(getPathRC(RemoteControl.red));});
    $('#rcGreen').click(function (event) {$.get(getPathRC(RemoteControl.green));});
    $('#rcYellow').click(function (event) {$.get(getPathRC(RemoteControl.yellow));});
    $('#rcBlue').click(function (event) {$.get(getPathRC(RemoteControl.blue));});
    $('#rcTV').click(function (event) {$.get(getPathRC(RemoteControl.tv));});
    $('#rcRadio').click(function (event) {$.get(getPathRC(RemoteControl.radio));});
    $('#rcText').click(function (event) {$.get(getPathRC(RemoteControl.text));});
    $('#rcNavHelp').click(function (event) { $.get(getPathRC(RemoteControl.help)); });

    $('#rcOne').click(function (event) { $.get(getPathRC(RemoteControl[1])); });
    $('#rcTwo').click(function (event) { $.get(getPathRC(RemoteControl[2])); });
    $('#rcThree').click(function (event) { $.get(getPathRC(RemoteControl[3])); });
    $('#rcFour').click(function (event) { $.get(getPathRC(RemoteControl[4])); });
    $('#rcFive').click(function (event) { $.get(getPathRC(RemoteControl[5])); });
    $('#rcSix').click(function (event) { $.get(getPathRC(RemoteControl[6])); });
    $('#rcSeven').click(function (event) { $.get(getPathRC(RemoteControl[7])); });
    $('#rcEight').click(function (event) { $.get(getPathRC(RemoteControl[8])); });
    $('#rcNine').click(function (event) { $.get(getPathRC(RemoteControl[9])); });
    $('#rcZero').click(function (event) { $.get(getPathRC(RemoteControl[0])); });

});

function DisplayBouquets(data)
{
    try{        
        var allBouquets = getBouquets(data);
        setupBouquets(allBouquets);
    }
    catch (err) { alert(err.message)}
}

function setupBouquets(data)
{
    $('#bouquetsList li').remove();
    $('#chnlList li').remove();

    $('#bouquetsList').append($('<li/>', {'data-role': "list-divider", text:'Bouquets' }));

    for (var i = 0; i < data.length; i++) {

        $('#bouquetsList').append($('<li/>', {

            /*css:{ 'background-color': data[i].selected ? "#369":"none"},'data-role': "list-divider"*/
        })
                    .append($('<a/>', { 
                        'href': uri.getServices + data[i].command,
                        'data-transition': 'slide',
                        'text': data[i].name,
                        'data-nav':'test',
                    })//end <a/>
                        .append($('<img/>', {
                            'src': "Images/empty.png" ,
                            'class': "ui-li-icon"
                        }))//end <a/>                        
        )); //end bouquetsList
    }

    $("#bouquetsList").listview("refresh");

    $("html, body").animate({ scrollTop: 0 }, "slow");

    $("#bouquetsList li a").click(function (event) {
        try {
            event.preventDefault();

            var bName = $(this).text();
            var htmlURI = $(this).attr('href');
            bouquet = { name: bName, uri: htmlURI };
            $.mobile.changePage('index.html#channels');
        }
        catch (err) { alert(err.message); };
    });
}

function DisplayChannels(groupName, data) {
    try {
        var channels = [];
        var lines = data.split('\n');
        channels = getChannels(groupName, lines);        
        setupChannels(channels);
    }
    catch (err) { alert(err.message) }
}

function setupChannels(data) {

    $('#chnlList li').remove();

    $('#chnlList').append($('<li/>', { 'data-role': "list-divider", text: 'Bouquet: ' + data.group }));

    for (var i = 0; i < data.channels.length; i++)
        $('#chnlList').append($('<li/>', {            
                        /*css: { 'background-color': data.channels[i].selected ? "#369" : "none" },
                        'data-role': "list-divider"*/
            //'data-theme': 'c',
                    })
                    .append($('<a/>', {
                        id: data.channels[i].selected ? 'selectItemLink' : '',
                        'class': data.channels[i].selected ?'ui-btn-up-b':'ui-btn-up-c',
                        'class': data.channels[i].selected ? 'ui-btn-up-b' : 'ui-btn-hover-c',
                        'data-theme':data.channels[i].selected ? 'b':'c',
                        'data-transition': 'slide',
                        'href': uri.receiver + uri.zapToPath + data.channels[i].command,
                        'text': data.channels[i].name,
                        css: { 'color': data.channels[i].selected ? '#006699' : 'none', 'font-weight': data.channels[i].selected ? 'bold' : 'normal' }
                    })//end <a/>
                        .append($('<img/>', {
                            'src': "Images/empty.png",
                            'class': "ui-li-icon",
                            css:{'background-color':'#333'},
                        }))//end <a/>                        
        )); //end bouquetsList

    $("#chnlList").listview("refresh");
    $("html, body").animate({ scrollTop: 0 }, "slow");
    
    //alert($("#selectItemLink").attr('class'));
    //$("#selectItemLink").click();
    //$("#selectItemLink").attr("data-theme", "b").removeClass("ui-btn-up-c").removeClass('ui-btn-hover-c').addClass("ui-btn-up-b").addClass('ui-btn-hover-b');

    $('#chnlList li a').bind('click', function () {
        $('#chnlList li a').attr("data-theme", "c").css('color', '#fff').css('font-weight', 'normal').removeClass("ui-btn-up-b").removeClass('ui-btn-hover-b').addClass("ui-btn-up-c").addClass('ui-btn-hover-c');
        $(this).attr("data-theme", "b").css('color', '#069').css('font-weight', 'bold').addClass('ui-link-inherit').removeClass("ui-btn-up-c").removeClass('ui-btn-hover-c').addClass("ui-btn-up-b").addClass('ui-btn-hover-b');
    });

    //window.scrollTo(0, 0);

    $("#chnlList li a").click(function (event) {
        try {
            event.preventDefault();

            var htmlURI = $(this).attr('href');
            $.get(htmlURI);
        }
        catch (err) { alert(err.message); };
    });

}

function getBouquets(data) {
    var bouquets = [];
    var lines = data.split('\n');

    for (var i = 0; i < lines.length - 1; i++) {
        var item = lines[i].split(';');
        bouquets.push({ command: item[0], name: item[1], selected: item[2] == 'selected' ? true : false });
    }
    return bouquets;
}

function getChannels(groupName, list) {
    var result;
    var chnls = [];
    var selected = false;
    var item;

    for (var i = 0; i < list.length - 1; i++) {
        item = list[i].split(';');
        selected = false;
        if (item[0] == currChannel) {
            selected = true;
        }

        chnls.push({ command: item[0], name: item[1], service: item[2], other: item[3], selected: selected });
    }

    result = { group: groupName, channels: chnls };
    return result;
}

function getAllServices(current, list) {
    var result;
    var services = [];
    var items = list.split('\n');
    var selected = false;
    
    for (var i = 0; i < items.length - 1; i++) {
        var item = items[i].split(';');
        if (item[0] == current)
            selected = true;

        services.push({ command: item[0], name: item[1], provider: item[2], other: item[3], selected: selected });
    }

    allServices = services;
    
    result = services;
    
    return result;
}

function getSelectedBouquet(bouquets) {
    for (var i = 0; i < bouquets.length; i++)
    {
        if (bouquets[i].selected == true)
            return bouquets[i];
    }
};

function removeTags(tag, source)
{
    var result;
    var t1 = content.split('<' + tag);
}